//
//  MuBWCViewController.m
//  KuWoCan
//
//  Created by hwd on 17/3/3.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "MuBWCViewController.h"
#import "MisstionCompleteDetailVC.h"
#import "PlanCell.h"
#import "PCCircle.h"
#import "NWMissionComRequest.h"
#import "MissonComModel.h"
#import "GradientProgressView.h"


@interface MuBWCViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)UITableView *tableV;

@property (nonatomic,strong) NSMutableDictionary *dataDic;  //原始数据

@property (nonatomic,strong) NSMutableArray *dataDicArr;  //梳理后的数据

@property (nonatomic,strong) NSMutableArray *dataModelArr;  //梳理后的数据

@property (nonatomic,strong) NSString *totalGoalNumStr;

@property (nonatomic,strong) NSString *totalRealNumStr;

@property (nonatomic,assign) CGFloat percent;




@end

@implementation MuBWCViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"目标完成情况";
    [self createRightButton:@"明细" selector:@selector(toDetail)];
    [self dataDicArr];
    [self dataModelArr];
    
    NWMissionComRequest *request = [[NWMissionComRequest alloc] init];
    [request startRequestGetMissionPlanWithUserId:_personId ? _personId :[Singleton shareInstance].userId];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            _dataDic = [NSMutableDictionary dictionaryWithDictionary:result];
            [self changeStructureOfTheData];
            [self.view addSubview:self.addTableView];
        } else {
            [SVProgressHUD showErrorWithStatus:message];
        }
    }];
}

- (NSMutableArray *)dataDicArr
{
    if (!_dataDicArr) {
        _dataDicArr = [NSMutableArray array];
        
    }
    return _dataDicArr;
}

- (NSMutableArray *)dataModelArr
{
    if (!_dataModelArr) {
        _dataModelArr = [NSMutableArray array];
        
    }
    return _dataModelArr;
}


- (void)changeStructureOfTheData
{
    NSArray *tempArr = @[@"tot",@"jan",@"feb",@"mar",@"apr",@"may",@"jun",@"jul",@"aug",@"sep",@"oct",@"nov",@"dec"];
    
    NSArray *dicAllKeys = [NSArray arrayWithArray:[_dataDic allKeys]];
    for (NSString *monthStr in tempArr)
    {
        NSMutableDictionary *tempDic = [NSMutableDictionary new];
        for (NSString*aKeyStr in dicAllKeys)
        {
            NSString *topKey  = [aKeyStr substringToIndex:3];
            if ([topKey isEqualToString:monthStr])
            {
                if (aKeyStr.length>6)
                {
                    NSString *endKey = [aKeyStr substringFromIndex:aKeyStr.length - 6];
                    if ([endKey isEqualToString:@"Actual"])
                    {
                        [tempDic setValue:[_dataDic valueForKey:aKeyStr] forKey:kActual];
                    }
                    else
                    {
                        [tempDic setValue:[_dataDic valueForKey:aKeyStr] forKey:kGoal];
                    }
                }
                else
                {
                    [tempDic setValue:[_dataDic valueForKey:aKeyStr] forKey:kGoal];
                }
                
                [tempDic setValue:[NSString stringWithFormat:@"%lu",(unsigned long)[tempArr indexOfObject:monthStr]] forKey:kMonthNum];
                [_dataDic removeObjectForKey:aKeyStr];
            }
        }
        [_dataDicArr addObject:tempDic];
    }
    
    _dataModelArr = [MissonComModel arrayOfModelsFromDictionaries:_dataDicArr];
    for (MissonComModel *model in _dataModelArr)
    {
        if ([model.monthNum isEqualToString:@"0"])
        {
            
            _totalGoalNumStr = model.goal;
            _totalRealNumStr = model.actual;
            
            if ([model.goal integerValue] == 0)
            {
                _percent = 0;
            }
            else
            {
                _percent =[model.actual floatValue]/[model.goal floatValue];
            }
            
            [_dataModelArr removeObject:model];
            break;
        }
    }
}

- (void)toDetail
{
    MisstionCompleteDetailVC *vc  = [[MisstionCompleteDetailVC alloc] init];
    vc.userId = _personId;
    [self.navigationController pushViewController:vc animated:YES];
}

-(UITableView *)addTableView//添加TableView
{
    if (!_tableV) {
        _tableV = [[UITableView alloc]initWithFrame:CGRectMake(0,0,SCREENW,SCREENH - 64) style:UITableViewStyleGrouped];
        _tableV.backgroundColor = [UIColor colorWithHexString:@"F6F7F8"];
        _tableV.dataSource = self;
        _tableV.delegate = self;
        _tableV.separatorStyle = UITableViewCellSelectionStyleNone;
    }
    return _tableV;
    
}
#pragma mark - TableView专区

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_dataModelArr)
    {
        return  _dataModelArr.count;
    }
    else
    {
        return 0;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 75*screenW_6;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 220;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [UIView new];
    headerView.backgroundColor = KwBlueColor;
//    PCCircle *_circle = [[PCCircle alloc] init];
//    _circle.percentage = _percent;    //百分比数值
//    _circle.lineWith = 10;       //线宽
//    _circle.fillColor = [UIColor colorWithHexString:@"fe9a69"];          //填充颜色
//    _circle.unfillColor = [UIColor colorWithHexString:@"77B9EC"];  //未填充颜色
//    _circle.startAngle =   -90;        //百分百的圆环起点
//    _circle.endInnerAngle = 270;     //百分百的圆环终点
//    //  circle.centerLable.text = @"111"; //中心标签的显示数值，默认为百分数
//    [headerView addSubview:_circle];
//    [_circle mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.equalTo(headerView.mas_centerX);
//        make.top.equalTo(@30);
//        make.size.mas_equalTo(CGSizeMake(130, 130));
//    }];
    GradientProgressView *circleProgress = [[GradientProgressView alloc] init];
    [headerView addSubview:circleProgress];
    [circleProgress mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(headerView.mas_centerX);
        make.top.equalTo(@30);
        make.size.mas_equalTo(CGSizeMake(130, 130));
    }];
    CGFloat progress = _percent;
    if (progress > 1) {
        progress = 1;
    }
    [circleProgress setProgress:progress animated:NO];

    UILabel *progressLabel = [UILabel new];
    progressLabel.font = KwFont(18);
    progressLabel.textAlignment = NSTextAlignmentCenter;
    progressLabel.textColor = KwColor(@"ffffff");
    progressLabel.text = [NSString stringWithFormat:@"%.0lf%%", _percent * 100];
    [headerView addSubview:progressLabel];
    [progressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.and.centerY.equalTo(circleProgress);
        make.left.lessThanOrEqualTo(circleProgress).offset(10);
        make.right.lessThanOrEqualTo(circleProgress).offset(-10);
    }];

    UILabel * _totalGoalNumLab = [UILabel new];
    _totalGoalNumLab.text = [NSString stringWithFormat:@"目标回款:%@元",_totalGoalNumStr];
    _totalGoalNumLab.font = KwFont(15);
    _totalGoalNumLab.textColor = [UIColor whiteColor];
    [headerView addSubview:_totalGoalNumLab];
    [_totalGoalNumLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(headerView.mas_centerX).offset(-10);
        make.top.equalTo(circleProgress.mas_bottom).offset(20);
        make.height.equalTo(@15);
    }];
    
    UILabel *_realNumLab = [UILabel new];
    _realNumLab.text = [NSString stringWithFormat:@"实际回款:%@元",_totalRealNumStr];
    _realNumLab.font = KwFont(15);
    _realNumLab.textColor = [UIColor whiteColor];
    [headerView addSubview:_realNumLab];
    [_realNumLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headerView.mas_centerX).offset(10);
        make.top.equalTo(_totalGoalNumLab.mas_top);
        make.bottom.equalTo(_totalGoalNumLab.mas_bottom);
    }];
    
    return headerView;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PlanCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell  = [[PlanCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[NSString stringWithFormat:@"cell%d",(int)indexPath.row]];
    }
    [cell loadCellWith:nil];
    
    MissonComModel *mdoel = _dataModelArr[indexPath.row];
    cell.model = mdoel;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //点击数据请求 改变默认地址 刷新列表
//    DetailJXKCViewController *detailVC = [[DetailJXKCViewController alloc]init];
//    [self.navigationController pushViewController:detailVC animated:YES];
}


@end
